<?php
namespace Home\Controller;
require_once COMMON_PATH."Api/WXPAY/lib/WxPay.Api.php";
use Common\Controller\CommonController;
class PayNotifyController extends CommonController {
	/**
	 * 验证
	 * @return array 返回数组格式的notify数据
	 */
public function notify(){
        	// 获取xml
        	$xml=file_get_contents('php://input', 'r');
        	// 转成php数组
        	$data=$this->toArray($xml);
        	//file_put_contents('a.txt', json_encode($data));
        	// 保存原sign
        	$data_sign=$data['sign'];
        	// sign不参与签名
        	//file_put_contents('b.txt', json_encode($data_sign));
        	unset($data['sign']);
        	$sign=$this->makeSign($data);
        	//file_put_contents('c.txt', json_encode($sign));
        	// 判断签名是否正确  判断支付状态
        	 if ($sign===$data_sign && $data['return_code']=='SUCCESS' && $data['result_code']=='SUCCESS') {
        		$result=$data;
        	}else{
        		$result=false;
        	} 
        	// 返回状态给微信服务器
        	if ($result) {
        		$str='<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
        	}else{
        		$str='<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>';
        	}
        	echo $str;
        	if($result){
        		$result1 = json_decode($this->decode($result['attach']),true);
        		if($result1['zt']=='1'){
        			file_put_contents('a.txt', $result1['zhuangtai']);
	        		$order=M('rob_orders');
	        		$olist=$order->where(array('order_id'=>$result1['order_id']))->find();//查询订单
	        		file_put_contents('b.txt', $result1['order_id']);
	        		if($olist){
	        			file_put_contents('c.txt', $result1['order_id']);
	        			$ginfo=M('rob_goods_orders');//查询订单商品
	        			$gg=$ginfo->where(array('order_id'=>$result1['order_id']))->find();
	        			$jiage=$gg['price']*$gg['num'];//总价
	        		    $orr['is_pay']=1;//是否付款   1 已付款
	        		    $orr['pay_money']=$jiage;  //付款金额
	        		    $orr['total_money']=$jiage;  //总价格
	        		    $orr['pay_time']=time();   //付款时间
	        		    $orr['order_status']=1;//订单状态
	        		    file_put_contents('d.txt', json_encode($orr));
	        		    $ores=$order->where(array('order_id'=>$result1['order_id']))->save($orr);//修改订单状态
	        		    if($ores){
	        		    	file_put_contents('z.txt', $ores);
	        		    }else{
	        		    	file_put_contents('j.txt', $ores);
	        		    }  
	        		}
        		}else{
        			file_put_contents('mm.txt',$result1['order_id']);
        			$order=M('rob_orders');//查询订单
        			$olist=$order->where(array('order_id'=>$result1['order_id']))->find();//查出订单
        			//助力拼抢的记录
        			$ginfo=M('rob_goods_orders');
        			$gg=$ginfo->where(array('order_id'=>$result1['order_id']))->find();//查询拼抢商品
        			file_put_contents('mm2.txt',json_encode($gg));
        			
        			$goods=M('goods')->where(array('goods_id'=>$gg['goods_id']))->find();
        			file_put_contents('mm3.txt',json_encode($goods));
        			//查询助力金额
        			$zhuliprice=$goods['zhuli_price'];
        			$log=M('rob_log');
        			$logarr['id']='';
        			$logarr['open_id']=$olist['open_id'];
        			$logarr['f_open_id']=$result1['open_id'];
        			$logarr['goods_orders_id']=$olist['order_id'];
        			$logarr['f_price']=$zhuliprice;
        			$logarr['created_at']=time();
        			$logarr['rob_order_id']=$olist['order_id'];
        			$logarr['score']=$zhuliprice;
        			$logarr['f_score']=$zhuliprice*10;
        			$lres=$log->add($logarr);//添加log表  第一次添加
        			file_put_contents('mm1.txt',$lres);
        			//助力加积分
        			$user=M('member')->where(array('openid'=>$olist['open_id']))->find();//查询购买人
        			$ulist['jifen']=$user['jifen']+1*$goods['zhuli_price'];//发起拼抢积分1*助力价格
        			$re=M('member')->where(array('openid'=>$olist['open_id']))->save($ulist);
        			file_put_contents('f.txt', $re);
        			$frr['id']='';//发起拼抢积分记录
        			$frr['open_id']=$olist['open_id'];
        			$frr['sz_type']=1;
        			$frr['content']='发起拼抢';
        			$frr['addtime']=time();
        			$frr['type']=2;
        			$frr['money']=$zhuliprice;
        			$ff=M('finance')->add($frr);
        			file_put_contents('g.txt', $ff);
        			file_put_contents('jj.txt',json_encode($olist));
        				//助力人数  +1
	        			$arr['zhulirenshu']=$olist['zhulirenshu']+1;
	        			$ores=$order->where(array('order_id'=>$result1['order_id']))->save($arr);
	        			file_put_contents('jj1.txt',$ores);//成功
	        			//助力人积分加10
	        			file_put_contents('zjj2.txt',$result1['open_id']);//
	        			$user1=M('member')->where(array('openid'=>$result1['open_id']))->find();
	        			file_put_contents('zjj1.txt',json_encode($user1));//
	        			$ulist1['jifen']=(float)$user1['jifen']+10*$goods['zhuli_price'];
	        			$re=M('member')->where(array('openid'=>$result1['open_id']))->save($ulist1);
	        			file_put_contents('mjj.txt',$re);//
	        			//助力拼抢积分记录
	        			$frr1['id']='';
	        			$frr1['open_id']=$result1['open_id'];
	        			$frr1['sz_type']=1;
	        			$frr1['content']='助力拼抢';
	        			$frr1['addtime']=time();
	        			$frr1['type']=2;
	        			$frr1['money']=10*$zhuliprice;
	        			$ff1=M('finance')->add($frr1);
	        			file_put_contents('jj2.txt',$ff1);
        		}
        	}
        }
	/**
	 * 将xml转为array
	 * @param  string $xml xml字符串
	 * @return array       转换得到的数组
	 */
	private function toArray($xml){
		//禁止引用外部xml实体
		libxml_disable_entity_loader(true);
		$result= json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
		return $result;
	}
	
	/**
	 * 生成签名
	 * @return 签名，本函数不覆盖sign成员变量，如要设置签名需要调用SetSign方法赋值
	 */
	private function makeSign($data){
		// 去空
		$data=array_filter($data);
		//签名步骤一：按字典序排序参数
		ksort($data);
		$string_a=http_build_query($data);
		$string_a=urldecode($string_a);
		//签名步骤二：在string后加入KEY
		$string_sign_temp=$string_a."&key=".'6d7b370094d879fb55ec3ed631a368bc';
		//签名步骤三：MD5加密
		$sign = md5($string_sign_temp);
		// 签名步骤四：所有字符转为大写
		$result=strtoupper($sign);
		return $result;
	}
	private function encode($string = '', $skey = 'cxphp') {
		$strArr = str_split ( base64_encode ( $string ) );
		$strCount = count ( $strArr );
		foreach ( str_split ( $skey ) as $key => $value )
			$key < $strCount && $strArr [$key] .= $value;
		return str_replace ( array (
				'=',
				'+',
				'/'
		), array (
				'O0O0O',
				'o000o',
				'oo00o'
		), join ( '', $strArr ) );
	}
	public function decode($string = '', $skey = 'cxphp') {
		$strArr = str_split ( str_replace ( array (
				'O0O0O',
				'o000o',
				'oo00o'
		), array (
				'=',
				'+',
				'/'
		), $string ), 2 );
		$strCount = count ( $strArr );
		foreach ( str_split ( $skey ) as $key => $value )
			$key <= $strCount && isset ( $strArr [$key] ) && $strArr [$key] [1] === $value && $strArr [$key] = $strArr [$key] [0];
		return base64_decode ( join ( '', $strArr ) );
	}
	
	
}